//log4js
import log4js from 'log4js'
import path from 'path'
let defaultConfig = {
  type: 'dateFile',
  filename: path.resolve('logs/info.log'),
  encoding: 'utf-8',
  layout: {
    type: 'pattern',
    pattern: '%d %p [%c] %h %m'
  },
  //split by day
  pattern: 'yyyy-MM-dd',
  // ends as '.log' 
  keepFileExt: true,
  //insert the date at the tail of name
  alwaysIncludePattern: true,
}
const config = {
  appenders: {
    default: defaultConfig,
    //debug appender
    debugAppender: {
      ...defaultConfig,
      filename: path.resolve('logs/debug.log'),
    },
    console: {
      type : 'console'
    },
    //debug filter
    debugFilter: {
      type: 'logLevelFilter',
      appender: 'debugAppender', // assign a specific appender
      level: 'debug', // lowest log level to catch
      maxLevel: 'debug', //highest log level to catch
    },
    //info filter
    infoFilter: {
      type: 'logLevelFilter',
      appender: 'default',
      level: 'info',
      maxLevel: 'info',
    },
    //warn filter
    warnFilter: {
      type: 'logLevelFilter',
      appender: 'default',
      level: 'warn',
      maxLevel: 'warn',
    },
    errorAppender: {
      ...defaultConfig,
      filename: path.resolve('logs/error.log'),
    },
    //error filter
    errorFilter: {
      type: 'logLevelFilter',
      appender: 'errorAppender',
      level: 'error',
      maxLevel: 'fatal',
    },
  },

  categories: {
    default: {   //default is a must
      appenders: ['console','infoFilter', 'warnFilter', 'errorFilter', 'debugFilter'],
      level: 'debug',
    }
  }
}

/**
 * get logger instance
 * @param {String} name default|error
 */
export const getLogger = (name) => {
  log4js.configure(config);
  return log4js.getLogger(name)
};
